package job

import (
	"context"
	"gcrontab/common"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

type LogManager struct {
	client        *mongo.Client
	logCollection *mongo.Collection
}

var G_logManager *LogManager

func InitLogManager() (err error) {
	ctx, _ := context.WithTimeout(context.Background(), time.Duration(common.G_conifg.MongoTimeOut)*time.Millisecond)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(common.G_conifg.MongoUrl))
	if err != nil {
		return
	}

	G_logManager = &LogManager{
		client:        client,
		logCollection: client.Database("cron").Collection("log"),
	}

	return
}

//获取日志列表
func (l *LogManager) GetLogList(name string, skip, limit int64) (logArr []*common.JobLog, err error) {
	logArr = make([]*common.JobLog, 0) //初始化，未查询到结果是返回
	filter := &common.JogLogFilter{JobName: name}
	sort := &common.JobLogSort{StartTime: -1}
	cursor, err := l.logCollection.Find(context.TODO(), filter, &options.FindOptions{Skip: &skip, Limit: &limit, Sort: sort})
	defer cursor.Close(context.TODO())
	if err != nil {
		return
	}
	for cursor.Next(context.TODO()) {
		jobLog := &common.JobLog{}
		err := cursor.Decode(jobLog)
		if err != nil {
			continue //有日志不合法
		}
		logArr = append(logArr, jobLog)
	}
	return logArr, nil
}
